<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\model\Customer as CustomerModel;
use think\Db;

class Customer extends Base
{

    public function __construct()
    {
        parent::__construct();
        $this->currentModel = new CustomerModel();
    }

    /**
     * 获取用户每日注册总数
     * @param $whereSql
     * @return mixed
     */
    public function getRegisterUserStatisList($whereSql)
    {

        $info = $this->currentModel
            ->field("date_format(create_time, '%Y-%m-%d') as registerHour, count(*) as counts")
            ->where($whereSql)
            ->group("registerHour")
            ->select();

        return $info;

    }

    /**
     * 根据token获取用户信息
     * @param $token
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function findByToken($token)
    {

        $info = $this->currentModel
            ->where('token', $token)
            ->find();

        return $info;

    }

    /**
     * 根据unionid获取用户信息
     * @param $unionid
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function findByUnionid($unionid)
    {

        $info = $this->currentModel
            ->where('unionid', $unionid)
            ->find();

        return $info;

    }

    /**
     * 根据openid查找
     * @param $openid
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function findByOpenid($openid)
    {

        $info = $this->currentModel
            ->where('openid', $openid)
            ->find();

        return $info;

    }

    /**
     * 根据每日优选的pid查找
     * @param $pid
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function findByYxPid($pid)
    {

        $info = $this->currentModel
            ->where('yx_pid', $pid)
            ->find();

        return $info;

    }

    /**
     * 根据nickname获取用户信息
     * @param $nickname
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function findByNickname($nickname)
    {

        $info = $this->currentModel
            ->where('nickname', $nickname)
            ->find();

        return $info;

    }

    /**
     * 用户列表
     * @param $condition
     * @return \think\Paginator
     */
    public function getCustomerList($condition)
    {

        $list = $this->currentModel
            ->where($condition['whereSql'])
            ->order('id desc')
            ->paginate(Config::get("paginate.list_rows"), false,
                ["query" => $condition['pageMap']]);

        return $list;

    }

    /**
     * 用户列表
     * @param $requestMap
     * @return \think\Paginator
     */
    public function getCustomerListByRequestMap($requestMap)
    {

        $list = $this->currentModel
            ->where(getMapFromRequest($requestMap['condition']))
            ->paginate(Config::get("paginate.list_rows"), false,
                ["query" => $requestMap['page']]);

        return $list;

    }

    /**
     * 获取会员下级所有人数
     * @param $customerId
     * @return float|string
     */
    public function getChildCustomerCountByCustomerId($customerId)
    {

        $count = $this->currentModel
            ->where('parent_customer_id', $customerId)
            ->count();

        return $count;

    }

    /**
     * 获取 我下级-最小收益总和
     * @param $customerId
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getDirectMinProfit($customerId)
    {

        $map['parent_customer_id'] = $customerId;

        $sum = $this->currentModel
            ->where($map)
            ->sum('history_profit');

        return $sum;

    }

    /**
     * 获取下级所有超级店长数量
     * @param $customerId
     * @return float|string
     */
    public function getAllSecondLevelNumber($customerId)
    {

        $map['current_level'] = config('enum.customerCurrentLevel.largeStore.value');

        $count = $this->currentModel
            ->where('(parent_customer_id = "' . $customerId . '" 
                || top_customer_id = "' . $customerId . '")')
            ->where($map)
            ->count();

        return $count;

    }

    /**
     * 获取 非直属有效店长(及以上级别)总数
     * @param $customerId
     * @return float|string
     */
    public function getIndirectValidNumber($customerId)
    {

        $map['top_customer_id'] = $customerId;

        $count = $this->currentModel
            ->where($map)
            ->where('current_level != ' . config('enum.customerCurrentLevel.ordinary.value'))
            ->where('history_profit > 0')
            ->count();

        return $count;

    }

    /**
     * 获取 非直属店长(及以上级别)总数
     * @param $customerId
     * @return float|string
     */
    public function getIndirectTotalNumber($customerId)
    {

        $map['top_customer_id'] = $customerId;

        $count = $this->currentModel
            ->where($map)
            ->where('current_level != ' . config('enum.customerCurrentLevel.ordinary.value'))
            ->count();

        return $count;

    }

    /**
     * 获取 直属有效店长(及以上级别)总数
     * @param $customerId
     * @return float|string
     */
    public function getDirectValidNumber($customerId)
    {

        $map['top_customer_id'] = $customerId;

        $count = $this->currentModel
            ->where($map)
            ->where('current_level != ' . config('enum.customerCurrentLevel.ordinary.value'))
            ->where('history_profit > 0')
            ->count();

        return $count;

    }

    /**
     * 获取 直属店长(及以上级别)总数
     * @param $customerId
     * @return float|string
     */
    public function getDirectTotalNumber($customerId)
    {

        $map['top_customer_id'] = $customerId;

        $count = $this->currentModel
            ->where($map)
            ->where('current_level != ' . config('enum.customerCurrentLevel.ordinary.value'))
            ->count();

        return $count;

    }

    /**
     * 获取 未结算金额
     * @param $customerId
     * @return mixed
     */
    public function getWaitingSettleNumber($customerId)
    {

        $orderStatus = config('enum.ddkOrderStatus.verifySuccess.value');

        // 未结算金额计算规则 first_customer_id 或者 second_customer_id
        // 或者 third_customer_id 为自己的 并且订单状态为 审核成功的
        $sql = "select sum(money) as waiting_settle_number from (
                select first_customer_profit as money from xd_order
                    where first_customer_id = ${customerId} and order_status=${orderStatus}
                union
                select second_customer_profit as money from xd_order
                    where second_customer_id = ${customerId} and order_status=${orderStatus}
                union
                select third_customer_profit as money from xd_order 
                  where third_customer_id = ${customerId} and order_status=${orderStatus}) a";

        return Db::query($sql);

    }

    /**
     * 验证更改等级条件是否满足
     * @param $customer
     * @param $level
     * @return mixed
     */
    public function checkChangeLevelCondition($customer, $level)
    {

        $returnData['success'] = false;
        $returnData['code'] = 200;

        // 如果历史收益小于 等级规则设定的（我-最小收益） 则报错
        if ($customer['history_profit'] < $level['min_profit']) {

            $returnData['code'] = 1;
            return $returnData;
        }

        // 获取 我下级-最小收益总和
        $directMinProfit = $this->getDirectMinProfit($customer['id']);
        // 如果我下级-最小收益总和 小于 等级规则设定的
        if ($directMinProfit < $level['direct_min_profit']) {

            $returnData['code'] = 2;
            return $returnData;
        }

        // 获取 非直属有效店长(及以上级别)总数
        $indirectValidNumber = $this->getIndirectValidNumber($customer['id']);
        // 如果 非直属有效店长(及以上级别)总数 小于 等级设定的
        if ($indirectValidNumber < $level['indirect_valid_number']) {

            $returnData['code'] = 4;
            return $returnData;
        }

        // 获取 非直属店长(及以上级别)总数
        $indirectTotalNumber = $this->getIndirectTotalNumber($customer['id']);

        // 如果 非直属店长(及以上级别)总数 小于 等级设定的
        if ($indirectTotalNumber < $level['indirect_total_number']) {

            $returnData['code'] = 5;
            return $returnData;
        }

        // 获取 直属有效店长(及以上级别)总数
        $directValidNumber = $this->getDirectValidNumber($customer['id']);
        // 如果 直属有效店长(及以上级别)总数 小于 等级设定的
        if ($directValidNumber < $level['indirect_valid_number']) {
            $returnData['code'] = 6;
            return $returnData;
        }

        // 获取 直属店长(及以上级别)总数
        $directTotalNumber = $this->getDirectTotalNumber($customer['id']);
        // 如果 直属店长(及以上级别)总数 小于 等级设定的
        if ($directTotalNumber < $level['indirect_valid_number']) {
            $returnData['code'] = 7;
            return $returnData;
        }

        // 获取团队内超级店长数量
        $allSecondLevelNumber = $this->getAllSecondLevelNumber($customer['id']);
        // 如果团队内超级店长数量 小于 等级规则设定的
        if ($allSecondLevelNumber < $level['all_second_level_number']) {

            $returnData['code'] = 3;
            return $returnData;
        }

        $returnData['success'] = true;

        return $returnData;

    }

    /**
     * 获取人气指数列表
     * @param $pointSortType
     * @param $pageNum
     * @param $pageSize
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getPopularityListForPage($pointSortType, $pageNum, $pageSize)
    {

        $map['current_level'] = config('enum.customerCurrentLevel.store.value');

        return $this->currentModel
            ->field('nickname, headimgurl, history_point, background_image, 
                    newest_like_json, sign, id customer_id, total_point')
            ->where($map)
            ->page($pageNum, $pageSize)
            ->order("total_point $pointSortType")
            ->select();
    }

    /**
     * 获取附近的人
     * @param $customer
     * @param $pageNum
     * @param $pageSize
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getNearbyListForPage($customer, $pageNum, $pageSize)
    {

        // 附近
        $likeGeohash = substr($customer['geohash'], 0, 3);

        $map['current_level'] = config('enum.customerCurrentLevel.store.value');

        $list = Db::name("customer")
            ->field('nickname, headimgurl, background_image, history_point, 
                    latitude, longitude, id customer_id, total_point')
            ->where("geohash like '%" . $likeGeohash . "%'
                and id != '" . $customer['id'] . "'")
            ->where($map)
            ->page($pageNum, $pageSize)
            ->select();

        return $list;
    }

    /**
     * 获取你邀请的所有人
     * @param $customerId
     * @param $pageNum
     * @param $pageSize
     * @return array|\PDOStatement|string|\think\Collection
     */
    public function getRecommendListForPage($customerId, $pageNum, $pageSize) {

        $map['parent_recommend_customer_id'] = $customerId;

        $list = $this->currentModel
            ->field("nickname, headimgurl, create_time, recommend_number")
            ->where($map)
            ->order('id desc')
            ->page($pageNum, $pageSize)
            ->select();

        return $list;

    }

    /**
     * 获取你邀请的所有人并且开店的数量
     * @param $customerId
     * @return float|string
     */
    public function getInvitedShopsCount($customerId) {

        $count = $this->currentModel
            ->where("parent_customer_id = '$customerId'")
            ->where([
                "current_level" => config("enum.customerCurrentLevel.store.value")
            ])
            ->count();

        return $count;
    }

    /**
     * 根据传入的条件获取邀请统计信息
     * @param $customerId
     * @param $date
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function getRecommendStatistics($customerId, $date) {

        $map["parent_recommend_customer_id"] = $customerId;
        $map["vip_date"] = $date;

        $count = $this->currentModel
            ->where($map)
            ->count();

        return $count;
    }
}